/* 显示遮罩层 */
function showOverlay() {
    $("#overlay").height(pageHeight());
    $("#overlay").width(pageWidth());

    // fadeTo第一个参数为速度，第二个为透明度
    // 多重方式控制透明度，保证兼容性，但也带来修改麻烦的问题
    $("#overlay").fadeTo(200, 0.5);
}

/* 隐藏覆盖层 */
function hideOverlay() {
    $("#overlay").fadeOut(200);
}

/* 当前页面高度 */
function pageHeight() {
    return document.body.scrollHeight;
}

/* 当前页面宽度 */
function pageWidth() {
    return document.body.scrollWidth;
}

$(document).ready(function () {
    Carousel.memo = {"enumName": "LiveProgramType", fatherId: 0, programList: "programList", "getChannel": "getChannel", "channelList": "channelList",
        platformRefer: "platformRefer",
        platSettings: "platSettings",
        platforms: "platforms",
        yesterdayEndTime: "yesterdayEndTime"
    }
    Carousel.lock = {flag: false};
    Carousel.Dao = (function () {
        var cache = {};

        function getDataByName(targetName) {
            var responseData = Carousel.ajaxManager.findResponseData(targetName);
            return responseData;
        }

        function getPrograms() {
            return getDataByName(Carousel.memo.programList).data;
        }

        function getChannel() {
            return getDataByName(Carousel.memo.getChannel).data;
        }

        function liveProgramType() {
            return getDataByName(Carousel.memo.enumName);
        }

        function channelList() {
            return getDataByName(Carousel.memo.channelList);
        }

        function getPlatformType() {
            return getDataByName(Carousel.memo.platforms)
        }

        function getPlatformRefer() {
            return getDataByName(Carousel.memo.platformRefer)
        }

        function getPlatSettings() {
            return getDataByName(Carousel.memo.platSettings)
        }

        function getFromCache(dataKey) {
            return cache[dataKey]
        }

        function putToCache(dataKey, data) {
            cache[dataKey] = data
        }


        return {
            getChannel: getChannel,
            liveProgramType: liveProgramType,
            channelList: channelList,
            getPrograms: getPrograms,
            getFromCache: getFromCache,
            putToCache: putToCache,
            getPlatformType: getPlatformType,
            getPlatformRefer: getPlatformRefer,
            getPlatSettings: getPlatSettings

        }

    })();
    Carousel.Formatter = (function () {
        function quickDateFormat(startTime) {
            return startTime.getFullYear() + "-" +
                (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
        }

        function reutrnNull() {
            // return "unknown"
            return "";
        }

        function formatDate(myDate) {
            var year = myDate.getFullYear();
            var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
            var day = ("0" + myDate.getDate()).slice(-2);
            var h = ("0" + myDate.getHours()).slice(-2);
            var m = ("0" + myDate.getMinutes()).slice(-2);
            var s = ("0" + myDate.getSeconds()).slice(-2);
            return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
        }

        function getFormatCopyRightEndTime(checkValue) {
            if (checkValue == null) {
                return reutrnNull();
            }
            if (typeof( checkValue ) == "string") {
                return checkValue;
            }
            if (checkValue <= 0) {
                return "---";
            } else {
                var date = new Date();
                date.setTime(parseInt(checkValue))
                return  formatDate(date);
            }
        }

        function getFormatPurchase(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                case -100:
                    return "免费";
                case 1:
                case 2:
                    return "收费";
                default:
                    return checkValue + ""
            }
        }

        function getFormatPublishStatus(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                    return "未发布";
                case 1:
                    return "已发布";
                case 2:
                    return "页面下线";
                case 3:
                    return "页面备用"
                default:
                    return checkValue + "";
            }
        }

        function getFormatGlobalPublishDate(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            return checkValue
        }

        function getTemplate(item) {
            var formatArr = [];
            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
            formatArr.push('<span class="contract-width120">' + getFormatCopyRightEndTime(item.copyrightEndTime) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPurchase(item.isPurchase) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPublishStatus(item.pagePublishStatus) + '</span>');
            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
        }

        return {
            copyRight: getFormatCopyRightEndTime,
            publishStatus: getFormatPublishStatus,
            globalPublishDate: getFormatGlobalPublishDate,
            purchase: getFormatPurchase,
            getTemplate: getTemplate,
            quickDateFormat: quickDateFormat,
            formatDate: formatDate
        }
    })();
    Carousel.Validate = (function () {
        var reg1 = /^\d+$/;
        var reg3 = /^[1-9]\d*$/;
        var reg2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
        var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;

        function checkNum(checkString) {
            return reg1.test(checkString)
        }

        function checkTimeFormat(checkString) {
            return reg4.test(checkString)
        }

        function checkPositive(checkString) {
            return reg3.test(checkString)
        }

        function checkDateFormat(checkString) {
            return reg2.test(checkString)
        }

        function defaultHandler(msg) {
            showTips({content: msg});
        }

        function batchCheck(checkArr) {
            if (checkArr == null) {
                checkArr = [];
            }
            if (checkArr.length == 0) {
                return true;
            }
            var flag = false;
            $.each(checkArr, function (index, checkData) {
                flag = baseCheck(checkData);
                if (!flag) {
                    return false;
                }
            })
            return flag;
        }

        function baseCheck(checkData) {
            var flag = false;
            if (!(checkData.value instanceof Array)) {
                checkData.value = [checkData.value];
            }
            if (!(checkData.error instanceof Array)) {
                checkData.error = [checkData.error];
            }
            if (checkData.handler == null) {
                checkData.handler = defaultHandler;
            }

            $.each(checkData.value, function (index, checkValue) {
                switch (checkData.type) {
                    case "time":
                        flag = checkTimeFormat(checkValue)
                        break;
                    case "date":
                        flag = checkDateFormat(checkValue);
                        break;
                    case "not_empty":
                        flag = checkValue != null && checkValue != "";
                        break;
                    case "eq":
                        flag = checkValue == checkData.other;
                        break;
                    case "ne":
                        flag = checkValue != checkData.other;
                        break;
                    case "gt":
                        flag = checkValue > checkData.other;
                        break;
                    case "ge":
                        flag = checkValue >= checkData.other;
                        break;
                    case "lt":
                        flag = checkValue < checkData.other;
                        break;
                    case "le":
                        flag = checkValue <= checkData.other;
                        break;
                    case "positive":
                        flag = checkPositive(checkValue)
                        break;
                    case "number":
                        flag = checkNum(checkValue)
                        break;
                    case "endsWith":
                        flag = checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                        break;
                    default :
                        break;
                }
                if (!flag) {
                    var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                    checkData.handler(hint);
                    return false;
                }
            })
            return flag
        }

        return {
            baseCheck: baseCheck,
            batchCheck: batchCheck,
            checkNum: checkNum,
            checkTimeFormat: checkTimeFormat,
            checkPositive: checkPositive,
            checkDateFormat: checkDateFormat
        }
    })();
    Carousel.Task = (function () {
        function platSettingsTask(channelId) {
            return {
                regName: Carousel.memo.platSettings,
                options: {
                    url: Carousel.urlConfig.platSettingsGetUrl,
                    type: "post",
                    data: {channelId: channelId},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platSettings + ":" + data.code);
                    }
                }
            }
        }

        function platformsTask() {
            return {
                regName: Carousel.memo.platforms,
                options: {
                    url: Carousel.urlConfig.configs,
                    type: "get",
                    data: {type: "PlayPlatform"},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platforms + ":" + data.code);
                    }
                }
            }
        }

        function getPlatformReferTask() {
            return {
                regName: Carousel.memo.platformRefer,
                options: {
                    url: Carousel.urlConfig.configs,
                    type: "get",
                    data: {type: "PlatformRefer"},
                    dataType: "json",
                    success: function (data) {
                        console.log(Carousel.memo.platformRefer + ":" + data.code);
                    }
                }
            }
        }

        function getProgramListTask() {
            var lDateFormat = Carousel.memo.dataTime.substr(0, 10);
            var sendData = {startDate: lDateFormat + " 00:00:00", endDate: lDateFormat + " 23:59:59", fatherId: Carousel.memo.fatherId, pageSize: 300}
            return {
                regName: Carousel.memo.programList,
                options: {
                    type: "post",
                    url: Carousel.urlConfig.programList,
                    data: sendData,
                    dataType: "json",
                    success: function (data) {
                        console.log("getProgramListTask success");
                    },
                    error: function (data) {
                        console.log("getProgramListTask fail");
                    }
                }
            }
        }


        function getChannelList() {
            return {
                regName: Carousel.memo.channelList,
                options: {
                    type: "post",
                    url: Carousel.urlConfig.channelList,
                    data: {pageSize: "3000"},
                    dataType: "json"
                }
            }
        }

        function getLiveProgramType() {
            return {
                regName: Carousel.memo.enumName,
                options: {
                    type: "get",
                    url: Carousel.urlConfig.configs,
                    dataType: "json",
                    data: {type: Carousel.memo.enumName}
                }
            }
        }


        function getClientNameArray(clientKeyArr) {
            var dataArr = [];
            var platformTypeResponse = Carousel.Dao.getPlatformType();
            $.each(platformTypeResponse.data, function (i, element) {
                if (clientKeyArr.indexOf(parseInt(element.key)) !== -1) {
                    dataArr.push(element.val);
                }
            })
            return dataArr;
        }

        function checkForQipuDataTask() {
            return {
                regName: "checkForQipu",
                options: {
                    url: Carousel.urlConfig.redirect,
                    dataType: "json",
                    type: "post"
                },
                handler: function (options) {
                    console.log(options.acceptArr);
                    var playControlArr = null;
                    var checkPlatforms = Carousel.Dao.getPlatformType().data;
                    var originalArr = Carousel.Dao.getFromCache("originalArr");
                    $.each(options.acceptArr, function (i, element) {
                        var original = originalArr[element.nodeIndex ];
                        if (element.responseData == null) {
                            original.illegal = true;
                            return true;
                        }
                        playControlArr = element.responseData["access_play_control"];
                        if (null == playControlArr && ( null == element.responseData["available_status"] || "OFFLINE_COPYRIGHT" === element.responseData["available_status"])) {
                            original.illegal = true;
                            return true;
                        }
                        if ($.isArray(playControlArr)) {
                            var temp = {};
                            $.each(playControlArr, function (index, elementChild) {
                                var platformObject = decodePlayPlatform(elementChild);
                                if (platformObject.platName != null) {
                                    temp[platformObject.platName] = platformObject;
                                }
                            })

                            original.controlObj = temp
                            var qipuPlatformData = [];
                            var qipuRegionData = [];
                            var hintMsgObj = {
                                missQIYIClient: false,
                                missPPSClient: false,
                                missQIYIRegion: false,
                                missPPSRegion: false
                            };
                            $.each(checkPlatforms, function (index, element) {
                                var ppsFlag = element.val.indexOf("PPS") !== -1;
                                if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                                    qipuPlatformData.push(element.val)
                                    if (ppsFlag) {
                                        hintMsgObj.missPPSClient = true;
                                    } else {
                                        hintMsgObj.missQIYIClient = true;
                                    }
                                }
                                if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                                    qipuRegionData.push(element.val);
                                    if (ppsFlag) {
                                        hintMsgObj.missPPSRegion = true;
                                    } else {
                                        hintMsgObj.missQIYIRegion = true;
                                    }
                                }
                            });
                            original["qipuPlatformData"] = qipuPlatformData;
                            original["qipuRegionData"] = qipuRegionData;
                            original["hintMsgObj"] = hintMsgObj;

                            original['displayName'] = 'haha';
                            console.log(element.responseData["id"] + "| qipuPlatformData : " + JSON.stringify(original["qipuPlatformData"]));
                            console.log(element.responseData["id"] + "| qipuRegionData: " + JSON.stringify(original["qipuRegionData"]));
                            console.log(element.responseData["id"] + "| hintMsgObj: " + JSON.stringify(original["hintMsgObj"]));
                        }
                    });
                    Carousel.lock.flag = false;
                }
            }
        }

        function decodePlayPlatform(elementChild) {
            var locationControl = null;
            var platformObject = {platName: null, locationArr: []}
            platformObject.platName = elementChild["play_platform"];
            platformObject.status = 'online';
            if (elementChild["default_control"] != null) {
                if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                    platformObject.status = "offline";
                }
            }
            if ($.isArray(elementChild["region_control"])) {
                $.each(elementChild["region_control"], function (indexRegion, regionElement) {
                    if ($.isArray(regionElement["location"])) {
                        $.each(regionElement["location"], function (j, child) {
                            if(child.hasOwnProperty("province_id")){
                                if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                    locationControl = regionElement["location_control"];
                                    if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                        platformObject.locationArr.push(child["province_id"]);
                                        console.log("break regionElement location");
                                    }
                                }
                            }
                        })
                    }
                })
            }
            return platformObject;
        }

        function removeDisAble() {
            $("button[name=btn_addType1]").removeAttr("disabled");
            $("button[name=btn_addType2]").removeAttr("disabled");
        }

        function sendBatchAddTaskCallBack(data) {
            removeDisAble();
            if (data.code == "A00000") {
                showTips({content: data.msg});
            } else {
                SystemDialog.queryAlert(data.msg);
            }

        }

        function sendBatchAddTask(ids) {
            return {
                regName: "sendBatchAddTask",
                options: {
                    url: Carousel.urlConfig.programBatchAddUrl,
                    type: "post",
                    dataType: "json",
                    data: {data: JSON.stringify(ids), beginTime: Carousel.memo.dataTime, fatherId: Carousel.memo.fatherId },
                    success: sendBatchAddTaskCallBack,
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                        removeDisAble()
                    }
                }
            }
        }

        return {
            sendBatchAddTask: sendBatchAddTask,
            getLiveProgramType: getLiveProgramType,
            getChannelList: getChannelList,
            getProgramListTask: getProgramListTask,
            checkForQipuDataTask: checkForQipuDataTask,
            removeDisAble: removeDisAble,
            platSettingsTask: platSettingsTask,
            platformsTask: platformsTask,
            getPlatformReferTask: getPlatformReferTask
        }
    })();
    Carousel.DialogManager = (function () {
        function initLoadLegoDlg() {
            $("#loadLegoMessage").dialog({
                title: "数据加载",
                autoOpen: false,
                width: 300,
                modal: true,
                dialogClass: 'alert',
                resizable: false
            });
        }

        function initBatchResponseDiv() {
            $("#batchResponseDiv").dialog({
                title: "数据核查汇总",
                autoOpen: false,
                width: 440,
                modal: true,
                dialogClass: 'alert',
                resizable: false,
                open: function (event) {
                    Carousel.Task.removeDisAble();
                },
                buttons: [
                    {
                        text: "继续",
                        click: function () {
                            Carousel.Operation.batchAdd();
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: "中断",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            })
        }

        function initDialog() {
            initBatchResponseDiv();
            initLoadLegoDlg();
            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
        }

        return{
            initDialog: initDialog
        }
    })();

    Carousel.EventManager = (function () {
        function queryProgram() {
            var queryObject = {};
            var parent = $("#addProgramView");
            var isLiveType = parent.find("select[name=insertType]").val() == "type2";
            var queryName = $.trim(parent.find("input[name=queryName]").val());
            var queryQipuId = $.trim(parent.find("input[name=qipuId]").val());
            queryObject.queryName = queryName;
            queryObject.queryQipuId = queryQipuId;
            queryObject.minTime = parent.find("input[name=minTime]").val();
            queryObject.maxTime = parent.find("input[name=maxTime]").val();
            queryObject.isLive = isLiveType;
            queryObject.startDate = parent.find("input[name=minDateTime]").val();
            queryObject.endDate = parent.find("input[name=maxDateTime]").val();
            queryObject.minVideoOrder = parent.find("input[name=minVideoOrder]").val();
            queryObject.maxVideoOrder = parent.find("input[name=maxVideoOrder]").val();
            queryObject.albumName = $.trim(parent.find("input[name=albumName]").val());
            var channelObj = $($("select[name=channel]").children()[$("select[name=channel]")[0].selectedIndex]);
            var contentTypeObj = $($("select[name=contentType]").children()[$("select[name=contentType]")[0].selectedIndex]);
            queryObject.kvPair = [];
            queryObject.kvPair.push({value: channelObj.val(), name: "filter_EQL_channel"});
            queryObject.kvPair.push({value: contentTypeObj.val(), name: contentTypeObj.attr("name") });
            Carousel.Grid.queryInsert(queryObject)
        }

        function batchInsertLiveProgram(tableId) {
            var gridElement = $("#" + tableId);
            var selectedtrArr = gridElement.find("tr[aria-selected=true]");
            var ids = [];
            $.each(selectedtrArr, function (i, element) {
                ids.push(parseInt($(element).attr("id")));
            })
            if (ids.length == 0) {
                return;
            }

            $("button[type=btn_addType1]").prop("disabled", "disabled");
            $("button[type=btn_addType2]").prop("disabled", "disabled");
            Carousel.Operation.startLiveSubmit(ids)
            console.log("ids " + JSON.stringify(ids));
        }


        function batchInsertLegoProgram(tableId) {
            var gridElement = $("#" + tableId);
            var selectedtrArr = gridElement.find("tr[aria-selected=true]");
            var ids = [];
            $.each(selectedtrArr, function (i, element) {
                ids.push(parseInt($(element).attr("id")));
            })
            if (ids.length == 0) {
                return;
            }
            $("button[type=btn_addType1]").prop("disabled", "disabled")
            $("button[type=btn_addType2]").prop("disabled", "disabled")
            // doSort ;
            ids = doSort(ids);
            Carousel.Operation.startSubmit(ids)
            console.log("ids " + JSON.stringify(ids));
        }

        function doSort(ids) {
            var responseData = Carousel.Dao.getFromCache("gridData1");
            var dataArr = responseData != null ? responseData.rows : [];
            var sortArr = [];
            $.each(dataArr, function (i, element) {
                if (ids.indexOf(element.qipuId) != -1) {
                    sortArr.push(element);
                }
            });
            sortArr.sort(function (a, b) {
                if (a.videoOrder != b.videoOrder) {
                    return a.videoOrder > b.videoOrder;
                }
                return a.globalPublishDate > b.globalPublishDate;
            });
            var afterSort = [];
            $.each(sortArr, function (i, element) {
                afterSort.push(element.qipuId);
            })
            console.log("ids " + JSON.stringify(ids) + " afterSort:" + JSON.stringify(afterSort));
            return afterSort;
        }

        function initEvent() {

        }

        function bindEvent() {
            var parent = $("#addProgramView");
            parent.find("button[name=queryProgram]").bind("click", function (event) {
                queryProgram();
            });
            parent.find("button[name=btn_addType1]").bind("click", function (event) {
                batchInsertLegoProgram("listAdd1");
            });
            parent.find("button[name=btn_addType2]").bind("click", function (event) {
                batchInsertLiveProgram("listAdd2")
            });

            var minElement = parent.find("input[name=minDateTime]");
            var maxElement = parent.find("input[name=maxDateTime]");

            minElement.datetimepicker({

                sliderAccessArgs: { touchonly: false },
                onClose: function (selectedDate) {
                    maxElement.datetimepicker("option", "minDate", selectedDate);
                    var toDate = new Date(selectedDate.replace(/-/g, "/"))
                    maxElement.datetimepicker("option", "minDateTime", toDate);
                }
            })
            maxElement.datetimepicker({

                sliderAccessArgs: { touchonly: false },
                onClose: function (selectedDate) {
                    minElement.datetimepicker("option", "maxDate", selectedDate);
                    var toDate = new Date(selectedDate.replace(/-/g, "/"))
                    minElement.datetimepicker("option", "maxDateTime", toDate);
                }
            })

            var selectTarget = $("#addProgramView").find("select[name=insertType]");
            selectTarget.bind("change", function (event) {
                var typeMode = selectTarget.val();
                $("#addType1").hide();
                $("#addType1").clearGridData();
                $("#addType2").hide();
                $("#addType2").clearGridData();
                if (typeMode == "type1") {
                    $("#addType1").show();
                    $("#dateTimeDiv").hide();
                    $("#div_new_type1").show();
                    $("#videoOrderDiv").show();
                    $("#div_albumName_typ1").show();
                } else {
                    $("#addType2").show();
                    $("#dateTimeDiv").show();
                    $("#div_new_type1").hide();
                    $("#videoOrderDiv").hide();
                    $("#div_albumName_typ1").hide();

                }
                $("input[type=text]").val("");
                $("input[name=minTime]").val(60);

            })
            selectTarget.change();
        }

        return {
            initEvent: initEvent,
            bindEvent: bindEvent
        }
    })();

    Carousel.Operation = (function () {
        var saveIds = null;
        var invalidArr = null;
        var sequeueArr = [];
        var timerId = -1;

        function checkMultiCallBack() {
            var data = Carousel.Dao.getPrograms();
            console.log("checkMultiCallBack wait to do" + JSON.stringify(data));
            var result = data.result;
            var multiArr = [];
            var hasUsedArr = [];
            $.each(result, function (i, element) {
                if (element.carouselEpisode > 0) {
                    hasUsedArr.push(element.carouselEpisode);
                }
            });
            $.each(saveIds, function (i, element) {
                if (hasUsedArr.indexOf(element) != -1) {
                    multiArr.push(element);
                }
            });

            var hintMsg = [];
            if (invalidArr != null && invalidArr.length > 0) {
                $.each(invalidArr, function (i, element) {
                    var idIndex = saveIds.indexOf(element);
                    if (idIndex != -1) {
                        saveIds.splice(idIndex, 1);
                    }
                    hintMsg.push(+"节目奇谱ID:<span style='color: red'>" + element + "</span>没有奇谱数据！");
                })
            }
            if (multiArr != null && multiArr.length > 0) {
                $.each(multiArr, function (i, element) {
                    hintMsg.push("节目奇谱ID:<span style='color: red'>" + element + "</span>,重复！");
                })
            }
            // var dataArr = $("#listAdd1").jqGrid('getData');
            var responseData = Carousel.Dao.getFromCache("gridData1");
            var dataArr = responseData != null ? responseData.rows : [];
            var missPPSClientArr = [];
            var missPPSRegionArr = [];
            var missQIYIClientArr = [];
            var missQIYIRegionArr = [];
            $.each(dataArr, function (i, element) {
                if (saveIds.indexOf(element.qipuId) != -1) {
                    if (element.hintMsgObj.missPPSClient === true) {
                        missPPSClientArr.push(element.qipuId);
                    }
                    if (element.hintMsgObj.missPPSRegion === true) {
                        missPPSRegionArr.push(element.qipuId);
                    }
                    if (element.hintMsgObj.missQIYIClient === true) {
                        missQIYIClientArr.push(element.qipuId);
                    }
                    if (element.hintMsgObj.missQIYIRegion === true) {
                        missQIYIRegionArr.push(element.qipuId);
                    }
                }
            })
            var remindLength = 0;
            var checkMsgArr = [ missPPSClientArr, missPPSRegionArr, missQIYIClientArr , missQIYIRegionArr ];
            var platformCheck = ["在PPS端没有上线，但会在PPS平台播出", "在PPS端有地域播控，但会在PPS平台全地域播出", "在IQIYI端没有上线，但会在IQIYI平台播出", "在IQIYI端有地域播控，但会在IQIYI平台全地域播出"];
            var platformMsg = [];
            $.each(checkMsgArr, function (i, checkArr) {
                if (checkArr.length > 0) {
                    remindLength = checkArr.length;
                    if (remindLength > 3) {
                        checkArr.length = 3;
                        platformMsg.push("节目奇谱ID " + checkArr.join(",") + "等" + remindLength + "个节目" + platformCheck[i]);
                    } else {
                        platformMsg.push("节目奇谱ID " + checkArr.join(",") + platformCheck[i]);
                    }
                }
            })
            if (platformMsg.length > 0) {
                platformMsg.push("是否确认添加？");
            }
            hintMsg = hintMsg.concat(platformMsg);
            if (hintMsg.length > 0) {
                $("#batchResponseDiv").find("div[sign=detail]").html(hintMsg.join("<br>"));
                $("#batchResponseDiv").dialog("open");
            } else {
                batchAdd();
            }
        }

        function batchAdd() {
            if (saveIds == null) {
                console.log("saveIds is empty");
                return;
            }
            $("button[name=btn_addType1]").attr("disabled", "disabled");
            $("button[name=btn_addType2]").attr("disabled", "disabled");
            console.log("sendId" + JSON.stringify(saveIds));
            var task = Carousel.Task.sendBatchAddTask(saveIds);
            Carousel.ajaxManager.push(task.regName, task.options, null, true);
            Carousel.ajaxManager.startLoad();
        }

        function checkMulti() {
            var task = Carousel.Task.getProgramListTask();
            Carousel.ajaxManager.removeTask(task.regName);
            Carousel.ajaxManager.push(task.regName, task.options);
            Carousel.ajaxManager.startLoad();
        }

        function doSequeue() {
            try {
                if (Carousel.ajaxManager.status == 2) {
                    if (sequeueArr.length > 0) {
                        var taskFun = sequeueArr.shift();
                        taskFun();
                    } else {
                        clearInterval(timerId);
                        timerId = -1;
                        checkMultiCallBack();
                    }
                }
            } catch (exception) {
                console.log("error", exception);
                Carousel.Task.removeDisAble();
            }

        }

        function startSubmit(ids) {
            saveIds = ids;
            // sequeueArr.push(checkQipuData);
            sequeueArr.push(checkMulti);
            $("button[name=btn_addType1]").attr("disabled", "disabled")
            timerId = setInterval(doSequeue, 1000);
        }

        function startLiveSubmit(ids) {
            saveIds = ids;
            invalidArr = [];
            batchAdd();
        }

        return {
            startSubmit: startSubmit,
            startLiveSubmit: startLiveSubmit,
            batchAdd: batchAdd
        }
    })()

    Carousel.Grid = (function () {
        function checkQipuPlatformControl(callback, ret) {
            var task = Carousel.Task.checkForQipuDataTask();
            var dataArr = [];
            var requestData = null;
            var currentTime = Date.now();

            Carousel.Dao.putToCache("originalArr", ret.result);
            $.each(ret.result, function (i, element) {
                requestData = {url: Carousel.urlConfig.getQiPuBaseUrl(element["qipuId"]), type: "get"};
                dataArr.push({"request": JSON.stringify(requestData), timeSign: currentTime });
            });
            Carousel.lock.flag = true;
            $("#loadLegoMessage").dialog("open");
            Carousel.ajaxManager.batchRequest(task.regName, task.options, dataArr, task.handler);
            var timerId = setInterval(function () {
                if (!Carousel.lock.flag) {
                    clearInterval(timerId);
                    $("#loadLegoMessage").dialog("close");
                    callback.call(this, ret);
                }
            }, 1000)
            Carousel.ajaxManager.startLoad();
        }

        function queryInsert(sendObject) {
            var checkArr = [];
            checkArr.push({value: sendObject.minTime, error: "最小时长需要数字格式", type: "positive"});
            checkArr.push({value: sendObject.minTime, error: "最小时长不能小于60秒", type: "ge", other: 60});
            if (sendObject.maxTime.length > 0) {
                checkArr.push({value: sendObject.maxTime, error: "最大时长需要数字格式", type: "positive"});
                checkArr.push({value: parseInt(sendObject.maxTime), error: "最小时长不能大于最大时长", type: "ge", other: parseInt(sendObject.minTime) });
            }
            if (sendObject.queryQipuId.length > 0) {
                checkArr.push({value: sendObject.queryQipuId, error: "qipuId需要数字格式", type: "positive"});
            }

            if (!sendObject.isLive) {
                if (sendObject.minVideoOrder.length > 0) {
                    checkArr.push({value: sendObject.minVideoOrder, error: "最小集数需非负整数", type: "number"});
                }
                if (sendObject.maxVideoOrder.length > 0) {
                    checkArr.push({value: sendObject.maxVideoOrder, error: "最大集数需要非负整数", type: "number"});
                }
                if (sendObject.minVideoOrder.length > 0 && sendObject.maxVideoOrder.length > 0) {
                    checkArr.push({value: parseInt(sendObject.maxVideoOrder), error: "终止集数必须大于等于开始集数", type: "ge", other: parseInt(sendObject.minVideoOrder) });
                }
                if (!Carousel.Validate.batchCheck(checkArr)) {
                    console.log("interrupt queryInsert")
                    return false;
                }
            }

            if (!Carousel.Validate.batchCheck(checkArr)) {
                console.log("interrupt queryInsert")
                return false;
            }
            if (sendObject.isLive) {
                fillGridType2(sendObject);
            } else {
                var task = Carousel.Task.platSettingsTask(Carousel.memo.fatherId);
                Carousel.ajaxManager.removeTask(task.regName);
                Carousel.ajaxManager.push(task.regName, task.options);
                Carousel.ajaxManager.afterLoadComplete(function () {
                    fillGridType1(sendObject);
                });
                Carousel.ajaxManager.startLoad();

            }
        }

        function fillGridType2(sendObj) {
            $("#listAdd2").clearGridData();
            var sendData = {startDate: "", endDate: ""};
            if (sendObj.endDate.length > 0) {
                if (!Carousel.Validate.checkDateFormat(sendObj.endDate)) {
                    showTips({content: "最大开始时间格式错误"})
                    return;
                }
                sendData.endDate = sendObj.endDate;
            }

            if (sendObj.startDate.length > 0) {
                if (!Carousel.Validate.checkDateFormat(sendObj.startDate)) {
                    showTips({content: "最小开始时间格式错误"})
                    return;
                }
                sendData.startDate = sendObj.startDate;
            } else {
                var defaultDate = new Date();
                sendData.startDate = Carousel.Formatter.formatDate(defaultDate);
                if (sendData.endDate.length > 0) {
                    if (sendData.startDate > sendData.endDate) {
                        sendData.startDate = "";
                    }
                } else {
                    if (sendData.startDate < Carousel.memo.dataTime) {
                        sendData.startDate = Carousel.memo.dataTime;
                    }
                }
            }
            sendData.pageSize = 50;
            sendData.qipuId = '';
            sendData.pname = '';
            sendData.maxTime = '';
            if (sendObj.queryQipuId.length > 0) {
                sendData.qipuId = sendObj.queryQipuId;
            }
            if (sendObj.queryName.length > 0) {
                sendData.pname = $.trim(sendObj.queryName);
            }
            sendData.minTime = sendObj.minTime;
            if (sendObj.maxTime.length > 0) {
                sendData.maxTime = sendObj.maxTime;
            }

            $(".norecords").hide()
            $("#listAdd2").setGridParam({url: Carousel.urlConfig.programLiveQueryUrl, loadtext: '加载中...', page: 1,
                loadui: "block", postData: sendData}).trigger("reloadGrid");
        }

        function getSearchParamsBySettings() {
            var response = Carousel.Dao.getPlatSettings();
            if (response == null) {
                console.log("setting error");
                return {};
            }
            var entity = response.data;
            var params = {};
            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Carousel.Dao.getPlatformType();
            $.each(platformTypeResponse.data, function (i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Carousel.Dao.getPlatformRefer();
            $.each(platformReferResponse.data, function (i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params))
            return params;
        }

        function fillGridType1(sendObj) {
            $("#listAdd1").clearGridData();
            var paramsData = getSearchParamsBySettings();
            //append base
            paramsData["filter_GTL_qipuId"] = 0;
            paramsData["t"] = 0;

            //page params
            paramsData["page.pageNo"] = 1;
            paramsData["page.order"] = "desc";
            paramsData["page.orderBy"] = "createTime";
            paramsData["page.pageSize"] = 30;

            if (sendObj.queryName.length > 0) {
                paramsData["filter_LIKES_displayName"] = sendObj.queryName
            }
            if (sendObj.queryQipuId.length > 0) {
                paramsData["filter_EQL_qipuId"] = sendObj.queryQipuId;
            }
            if (sendObj.minTime.length > 0) {
                paramsData["filter_GEL_duration"] = parseInt(sendObj.minTime) * 1000;
            }
            if (sendObj.maxTime.length > 0) {
                paramsData["filter_LEL_duration"] = parseInt(sendObj.maxTime) * 1000;
            }

            if (sendObj.minVideoOrder.length > 0) {
                paramsData["filter_GEL_videoOrder"] = parseInt(sendObj.minVideoOrder);
            }
            if (sendObj.maxVideoOrder.length > 0) {
                paramsData["filter_LEL_videoOrder"] = parseInt(sendObj.maxVideoOrder);
            }
            if (sendObj.albumName.length > 0) {
                paramsData["filter_LIKES_albumDisplayName"] = sendObj.albumName
            }
            $.each(sendObj.kvPair, function (i, element) {
                if (element.value.length > 0) {
                    paramsData[element.name] = element.value;
                }
            })

            var requestData = {url: Carousel.Constant.thirdUrl_apis_search_area_url, type: "get", params: paramsData, needCookie: true};
            var parentView = $("#addProgramView");
            parentView.find("button[name=queryProgram]").attr("disable", "disabled");

            $("#listAdd1").setGridParam({page: 1, url: Carousel.urlConfig.redirect, loadtext: '加载中...', pageSize: 50,
                // datatype:"json",
                loadui: "block", postData: {"request": JSON.stringify(requestData), timeSign: Date.now()}}).trigger("reloadGrid");

        }

        function wrapColor(rowObject, value) {
            if (rowObject.hintMsgObj == null) {
                console.log("rowObject.hintMsgObj is null" + rowObject.qipuId)
                return value;
            }
            if (rowObject.hintMsgObj.missPPSClient || rowObject.hintMsgObj.missQIYIClient) {
                return  '<span style="color:red;">' + value + '</span>';
            } else if (rowObject.hintMsgObj.missPPSRegion || rowObject.hintMsgObj.missQIYIRegion) {
                return  '<span style="color:#ffa800;">' + value + '</span>';
            }
            return value
        }

        function showNoResult(dataLength) {
            var jqGridTarget = $("#listAdd1");
            var parentElement = jqGridTarget.parent();
            if (parentElement.find(".norecords").html() == null) {
                parentElement.append('<div class="norecords">没有符合数据</div>');
                parentElement.find(".norecords").hide();
            }
            if (dataLength == 0) {
                parentElement.find(".norecords").show();
            } else {
                parentElement.find(".norecords").hide();
            }
        }

        function initListAddType1Grid() {
            var _jqGrid3 = $("#listAdd1").jqGrid({
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeProcessing: function (data, status, xhr) {
                    var self = this;
                    checkQipuPlatformControl(function (data) {
                        var filterResult = [];
                        $.each(data.result, function (i, element) {
                            if (!element.illegal) {
                                filterResult.push(element)
                            } else {
                                console.log("illegal:" + element.qipuId);
                            }
                        })


                        var fillData = {"total": data.totalPages, "page": data.pageNo, "records": data.totalCount, "rows": filterResult};
                        Carousel.Dao.putToCache("gridData1", fillData);
                        $("#listAdd1")[0].addJSONData(fillData);
                        showNoResult(fillData.rows.length);
                        // $("#listAdd1").triggerHandler("jqGridLoadComplete", [fillData])
                    }, data.data);
                    return false;
                },
                serializeGridData: function (postData) {
                    if (postData.request != null) {
                        var requestData = JSON.parse(postData.request);
                        requestData.params["page.pageNo"] = postData["page.pageNo"];
                        postData.request = JSON.stringify(requestData)
                    }
                    return postData
                },
                jsonReader: {
                    id: "qipuId",
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records"
                },
                multiselect: true,

                mtype: "post",
                datatype: "json",
                width: 1300,
                height: 450,
                rowNum: 30,
                caption: "点播列表",
                colNames: ["奇谱ID", "节目名称", "专辑ID", "频道", "发行时间", "时长", "发布状态", "版权到期时间", "付费", "操作"],
                colModel: [
                    {//节目ID
                        name: "qipuId",
                        index: 'qipuId',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var plusUrl = Carousel.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                            return "<a target='_blank' href='" + plusUrl + "' >" + rowObject.qipuId + "</a>";
                        }
                    }
                    ,
                    {//节目名称
                        name: "displayName",
                        index: 'displayName',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, cellvalue)
                        }
                    },
                    {//专辑ID
                        name: "albumId",
                        index: 'albumId',
                        title: false,
                        width: 100,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue > 0) {
                                var plusUrl = "http://lego.iqiyi.com/apis/search/search-area?filter_EQL_entityId=" + cellvalue + "&t=1";
                                return "<a target='_blank' href='" + plusUrl + "' >" + cellvalue + "</a>";
                            } else {
                                return "";
                            }
                        }
                    },
                    {//频道
                        name: "channelName",
                        index: 'channelName',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, cellvalue)
                        }
                    }
                    ,
                    {//发行时间
                        name: "globalPublishDate",
                        index: 'globalPublishDate',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, Carousel.Formatter.globalPublishDate(cellvalue))

                        }
                    },
                    {//时长
                        name: "duration",
                        index: 'duration',
                        title: false,
                        width: 60,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var calculateDuration = ( cellvalue / 1000 >> 0);
                            return wrapColor(rowObject, tranDurationFormat(calculateDuration));
                        }
                    },
                    {//发布状态
                        name: "pagePublishStatus",
                        index: 'pagePublishStatus',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, Carousel.Formatter.publishStatus(cellvalue));
                        }
                    },
                    {//版权到期时间
                        name: "copyrightEndTime",
                        index: 'copyrightEndTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, Carousel.Formatter.copyRight(cellvalue));
                        }
                    },
                    {//付费
                        name: "bossStatus",
                        index: 'bossStatus',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        hidden: true,
                        formatter: function (cellvalue, options, rowObject) {
                            return wrapColor(rowObject, Carousel.Formatter.purchase(cellvalue));
                        }
                    },
                    {//操作
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        hidden: true
                    }
                ],
                pager: "#pagerAdd1"
            })
        }

        function initListAddType2Grid() {
            var _jqGrid4 = $("#listAdd2").jqGrid({
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                jsonReader: {
                    id: "qipuId"
                },
                multiselect: true,
                loadComplete: function () {
                    var jqGridTarget = $("#listAdd2");
                    var re_records = jqGridTarget.getGridParam('records');
                    var parentElement = jqGridTarget.parent()
                    if (re_records == 0 || re_records == null) {
                        if (parentElement.find(".norecords").html() == null) {
                            parentElement.append('<div class="norecords">没有符合数据</div>');
                            parentElement.find(".norecords").hide();
                        }
                        parentElement.find(".norecords").show();
                    } else {
                        parentElement.find(".norecords").hide();
                    }
                },

                mtype: "post",
                datatype: "json",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                width: 860,
                height: 450,
                rowNum: 50,
                caption: "直播列表",
                colNames: ["奇谱ID", "节目名称", "开始时间", "结束时间", "时长", "节目类型", "付费", "所属频道"],
                colModel: [
                    {
                        name: "qipuId",
                        index: 'qipuId',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var plusUrl = Carousel.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                            return "<a target='_blank' href='" + plusUrl + "'>" + rowObject.qipuId + "</a>";
                        }
                    }
                    ,
                    {
                        name: "pname",
                        index: 'pname',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "startPlayTime",
                        index: 'startPlayTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "endPlayTime",
                        index: 'endPlayTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        index: 'itemTime',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var duration = (new Date(rowObject.endPlayTime.replace(/-/g, "/")).getTime() - new Date(rowObject.startPlayTime.replace(/-/g, "/")).getTime()) / 1000;
                            return tranDurationFormat(duration);
                        }
                    },
                    {
                        //节目类型,
                        name: "type",
                        index: 'type',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var ret = []
                            var enumNameData = Carousel.Dao.liveProgramType();
                            $.each(enumNameData.data, function (index, element) {
                                if (cellvalue == element.key) {
                                    ret = element.descr;
                                    return true;
                                }
                            })
                            return ret
                        }
                    },
                    {
                        //付费
                        name: "bossStatus",
                        index: 'bossStatus',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var enumValue = "";
                            switch (cellvalue) {
                                case "FREE":
                                    enumValue = "免费";
                                    break;
                                case "PAIED_NOT_AVAILABLE":
                                    enumValue = "付费未划价";
                                    break;
                                case "PAIED_AVAILABLE":
                                    enumValue = "付费已划价";
                                    break;
                                default:
                                    break;
                            }
                            return enumValue;
                        }
                    },
                    {
                        //所属频道
                        name: "channelName",
                        index: 'channelName',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center"
                    }
                ],
                pager: "#pagerAdd2"
            })
        }

        function tranDurationFormat(duration) {
            var darArr = [];
            var originalDuration = duration;
            darArr.push(duration % 60);
            duration = ( duration - duration % 60) / 60;
            if (duration > 0) {
                darArr.push(duration % 60);
            }
            duration = ( duration - duration % 60) / 60;
            if (duration > 0) {
                darArr.push(duration % 24);
            }
            duration = ( duration - duration % 24) / 24;
            if (duration > 0) {
                darArr.push(duration);
            }
            var retValue = "";
            switch (darArr.length) {
                case 4:
                    retValue = darArr[3] + "天";
                case 3:
                    retValue += darArr[2] + "时";
                case 2:
                    retValue += darArr[1] + "分";
                case 1:
                    retValue += darArr[0] + "秒";
                    break;
            }
            return retValue;
        }

        function initGrid() {
            initListAddType1Grid();
            initListAddType2Grid();
        }

        return {
            initGrid: initGrid,
            queryInsert: queryInsert,
            tranDurationFormat: tranDurationFormat
        }

    })();
})

$(document).ready(function () {
    Carousel.DialogManager.initDialog();
    Carousel.EventManager.initEvent();

    Carousel.ajaxManager.afterLoadComplete(function () {
        var channelData = Carousel.Dao.getChannel();
        if (channelData.liveType != 3) {
            showTips({content: "当前频道不是轮播台"});
            setTimeout(function () {
                window.location.href = "/epg/program_list.html?fatherId=" + Carousel.memo.fatherId;
            }, 2000)
            return;
        }

        Carousel.Grid.initGrid();
        Carousel.EventManager.bindEvent();
        Carousel.Task.removeDisAble();
    });


    var fatherId = Com.url.getParameter("fatherId")
    if (fatherId != null) {
        Carousel.memo.fatherId = parseInt(fatherId);
        Carousel.ajaxManager.push(Carousel.memo.getChannel, {
            type: "post",
            url: Carousel.urlConfig.channelGet,
            dataType: "json",
            data: {id: fatherId}
        })
    }

    var startTime = Com.url.getParameter("startTime")
    if (startTime == null) {
        showTips({content: "参数异常"})
        return;
    }

    var taskArr = [];
    taskArr.push(Carousel.Task.getLiveProgramType());
    taskArr.push(Carousel.Task.platformsTask());
    taskArr.push(Carousel.Task.platSettingsTask(fatherId));
    taskArr.push(Carousel.Task.getPlatformReferTask());
    $.each(taskArr, function (index, element) {
        Carousel.ajaxManager.push(element.regName, element.options);
    })
    Carousel.memo.dataTime = Carousel.Formatter.formatDate(new Date(startTime.replace(/-/g, "/")))
    Carousel.ajaxManager.startLoad();
})
